var admin = {
    // app初始化容器
    appContainer: $('#admin-content'),

    userData: null,

    // 程序初始化
    init: function () {
        this.isLogin();
    },

    isLogin: function () {
        var user = server.storage('user');
        if (user._id) this.userData = user;
        this.initTop();
        this.router();
    },

    initTop: function () {
        var top = template.render(topTpl)({user: admin.userData});
        $("#top").html(top);
    },

    router: function () {

        var router = new Router({
            root: '/admin',
            routes: {
                '': function () {
                    admin.loginPage.init();
                },
                '/': function () {
                    admin.loginPage.init();
                },
                '/login': function () {
                    admin.loginPage.init();
                },
                '/tag': function () {
                    admin.tagPage.init();
                },
                '/publish': function () {
                    admin.publishPage.init();
                },
                '/signin': function () {
                    admin.signinPage.init();
                },
                '/collects': function () {
                    admin.collectsPage.init();
                }
            },
        });

        // 如果没有登录则去根目录
        if (!this.userData) router.go('/');

        router.start();
    },

    // 登录
    loginPage: {

        init: function () {
            this.render();
            this.events();
        },

        events: function () {
            var self = this;
            $("#loginForm").submit(function () {
                var param = {};
                param.username = this.username.value;
                param.password = this.password.value;
                self.login(param);
                return false;
            })

            // $('.login').on('click', '#logout', function(event) {

            // });
        },

        // 登录
        login: function (data) {
            var self = this;
            server.ajax({
                url: 'LOGIN',
                data: data,
                type: 'post',
                success: function (res) {
                    admin.userData = res.data;
                    server.storage('user', res.data);
                    self.render();
                    admin.initTop();
                }
            })
        },

        render: function () {
            var user = template.render(userTpl)({user: admin.userData});
            admin.appContainer.html(user);
        }
    },

    // 注册
    signinPage: {
        init: function () {
            this.render();
            this.events();
        },

        events: function () {
            var self = this;
            $("#signinForm").submit(function () {
                var param = {};
                param.username = this.username.value;
                param.photo = this.photo.value;
                param.nickname = this.nickname.value;
                self.singup(param);
                return false;
            })
        },

        // 登录
        singup: function (data) {
            var self = this;
            server.ajax({
                url: 'SIGNIN',
                data: data,
                type: 'post',
                success: function (res) {
                    alert('注册成功');
                    self.render();
                }
            })
        },

        render: function () {
            var singn = template.render(singginTpl)({});
            admin.appContainer.html(singn);
        }
    },

    // 发布博客
    publishPage: {
        init: function () {
            this.render();
            this.getTag();
            this.events();
        },

        editor: null,

        getTag: function () {
            var self = this;
            server.ajax({
                url: 'GET_TAG',
                success: function (res) {
                    var tags = res.data;
                    var html = '';

                    tags.map(function (value, index) {
                        html += '<a class="tag" href="#">' + value.name + '</a>';
                    })

                    $("#pubTag").html(html);
                }
            })
        },

        events: function () {
            var self = this;

            // 提交文章
            admin.appContainer.on('click', '#publishBtn', function () {
                var title = $("#pubTitle").val();
                var tag = $("#pubTag").find('.active');
                var description = $("#description").val();
                var content = self.editor.getElement('previewer').body.innerHTML;
                var markdown = self.editor.getElement('editor').body.innerHTML;

                if (!title || !tag.length || !content || !description) {
                    alert('有东西没填');
                    return false;
                }
                ;

                var tags = [];
                tag.each(function (index, el) {
                    tags.push($(this).text());
                });

                self.publish({
                    title: title,
                    tag: JSON.stringify(tags),
                    description: description,
                    content: content,
                    markdown: markdown
                });
            });

            admin.appContainer.on('click', '.publish .tag', function (event) {
                $(this).toggleClass('active');
                return false;
            });
        },

        publish: function (data) {
            var self = this;
            server.ajax({
                url: 'ADD_BLOG',
                data: data,
                type: 'post',
                success: function (res) {
                    server.storage('epiceditor', 'null');
                    server.storage('__draft-epiceditor', 'null');
                    alert('发布成功');
                    self.render();
                }
            })
        },

        render: function () {
            admin.appContainer.html(publishTpl);

            var editor = new EpicEditor({
                container: 'epiceditor',
                basePath: '/static/css'
            });

            editor.load();
            this.editor = editor;
        }
    },

    // 收藏
    collectsPage: {
        init: function () {
            this.render();
            var self = this;
            $("#collectsForm").submit(function () {
                var param = {};
                param.title = this.title.value;
                param.text = this.text.value;
                param.url = this.url.value;
                self.send(param);
                return false;
            })
        },

        send: function (data) {
            var self = this;
            server.ajax({
                url: 'ADD_COLLECTS',
                data: data,
                type: 'post',
                success: function (res) {
                    alert('添加成功');
                    self.render();
                }
            })
        },

        render: function () {
            var html = template.render(collectsTpl)({});
            admin.appContainer.html(html);
        }
    },

    // 标签管理
    tagPage: {
        init: function () {
            this.getTag();

            var self = this;

            admin.appContainer.on('click', '#tagSubmit', function () {
                var param = {tag: $("#tag-name").val(), type: 'add'}
                self.upTag(param);
            });

            admin.appContainer.on('dblclick', '.taglist a', function () {
                if (window.confirm('确认删除这个标签吗？')) {
                    var param = {tag: $(this).text(), type: 'rem'}
                    self.upTag(param);
                }
            });
        },

        getTag: function () {
            var self = this;
            server.ajax({
                url: 'GET_TAG',
                success: function (res) {
                    self.render(res.data);
                }
            })
        },

        upTag: function (data) {
            var self = this;
            server.ajax({
                url: 'ADD_TAG',
                data: data,
                type: 'post',
                success: function (res) {
                    self.getTag();
                }
            })
        },

        render: function (data) {
            var html = template.render(tagTpl)({list: data});
            admin.appContainer.html(html);
        }
    }
}

function logout() {
    admin.userData = '';
    server.storage('user', 'null');
    location.href = '/admin/login';
    return false;
}

var tagTpl = '' +
    '<div class="min-width">' +
    '    <div class="taglist">' +
    '    <p>提示: 双击标签可进行删除</p>' +
    '    {{each list as item }}' +
    '       <a class="tag">{{item.name}}</a>' +
    '    {{/each}}' +
    '    </div><br/><hr/>' +
    '    <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label textfield-demo">' +
    '      <input class="mdl-textfield__input" type="text" id="tag-name"/>' +
    '      <label class="mdl-textfield__label">填写标签</label>' +
    '    </div><br/>' +
    '  <button id="tagSubmit" class="mdl-button mdl-js-button mdl-button--raised mdl-button--accent">添加标签</button>' +
    '</div>'


var topTpl = '' +
    '{{if !user }}' +
    '   <a class="mdl-navigation__link stateful" href="/login" >登录</a>' +
    '{{else}}' +
    '  <a class="mdl-navigation__link stateful" href="/user">用户管理</a>' +
    '  <a class="mdl-navigation__link stateful" href="/blog">博客管理</a>' +
    '  <a class="mdl-navigation__link stateful" href="/tag">标签管理</a>' +
    '  <a class="mdl-navigation__link stateful" href="/collects">添加收藏</a>' +
    '  <a class="mdl-navigation__link stateful" href="/publish">发表文章</a>' +
    '  <a class="mdl-navigation__link stateful" href="/signin">添加新同学</a>' +
    '  <a class="mdl-navigation__link stateful" href="/login" >{{user.nickname}}</a>' +
    '{{/if}}';

var userTpl = '' +
    '<div class="login">' +
    '{{if !user}}' +
    '  <form id="loginForm">' +
    '    <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label textfield-demo">' +
    '      <input class="mdl-textfield__input" type="text" name="username" required="required"/>' +
    '      <label class="mdl-textfield__label" >账号</label>' +
    '    </div>' +
    '    <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label textfield-demo">' +
    '      <input class="mdl-textfield__input" type="password" name="password" required="required"/>' +
    '      <label class="mdl-textfield__label">密码</label>' +
    '    </div>' +
    '    <button class="mdl-button mdl-js-button mdl-button--raised mdl-button--accent mdl-js-ripple-effect">' +
    '      登录' +
    '    </button>' +
    '  </form>' +
    '{{else}}' +
    '<h4>欢迎 {{user.nickname}}  <a href="/" onClick="logout()" id="logout">[退出]</a></h4>' +
    '{{/if}}' +
    '</div>';

var singginTpl = '' +
    '<div class="login">' +
    '  <form id="signinForm">' +
    '    <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label textfield-demo">' +
    '      <input class="mdl-textfield__input" type="text" name="username" required="required"/>' +
    '      <label class="mdl-textfield__label">账号...</label>' +
    '    </div>' +
    '    <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label textfield-demo">' +
    '      <input class="mdl-textfield__input" type="text" name="nickname" required="required"/>' +
    '      <label class="mdl-textfield__label">昵称...</label>' +
    '    </div>' +
    '    <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label textfield-demo">' +
    '      <input class="mdl-textfield__input" type="text" name="photo" required="required"/>' +
    '      <label class="mdl-textfield__label">头像...</label>' +
    '    </div>' +
    '  <button type="submit" class="mdl-button mdl-js-button mdl-button--raised mdl-button--accent">注册</button>' +
    '  </form>' +
    '</div>'

var collectsTpl = '' +
    '<div class="login">' +
    '  <form id="collectsForm">' +
    '    <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label textfield-demo">' +
    '      <input class="mdl-textfield__input" type="text" name="title" required="required"/>' +
    '      <label class="mdl-textfield__label">标题...</label>' +
    '    </div>' +
    '    <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label textfield-demo">' +
    '      <textarea class="mdl-textfield__input" type="text" name="text" required="required"/>' +
    '      <label class="mdl-textfield__label">推荐语...</label>' +
    '    </div>' +
    '    <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label textfield-demo">' +
    '      <input class="mdl-textfield__input" type="text" name="url" required="required"/>' +
    '      <label class="mdl-textfield__label">url...</label>' +
    '    </div>' +
    '  <button type="submit" class="mdl-button mdl-js-button mdl-button--raised mdl-button--accent">确定</button>' +
    '  </form>' +
    '</div>'

var publishTpl = '' +
    '<div class="publish">' +
    '<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label textfield-demo">' +
    '  <div id="pubTag" > </div>' +
    '</div>' +
    '<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label textfield-demo">' +
    '  <input class="mdl-textfield__input" type="text" id="pubTitle" />' +
    '  <label class="mdl-textfield__label">标题</label>' +
    '</div>' +
    '<div class="mdl-textfield mdl-js-textfield textfield-demo">' +
    '  <textarea class="mdl-textfield__input" type="text" rows= "3" id="description" ></textarea>' +
    '  <label class="mdl-textfield__label">文章描述</label>' +
    '</div>' +
    '<div id="epiceditor"></div>' +
    '<button id="publishBtn" class="mdl-button mdl-js-button mdl-button--raised mdl-button--accent">发布</button>' +
    '</div>';


